<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <!-- import CSS -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <input type="text" placeholder="想说啥就说啥" v-model="weibo.content">
    <!--action:设置文件上传地址
        name：设置参数名称
        limit:设置上传文件的数量
        :on-success：图片上传到磁盘成功事件-->
    <el-upload
            action="/upload"
            name="picFile"
            limit="1"
            list-type="picture-card"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <el-button @click="insert()">发布微博</el-button>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
  new Vue({
    el: '#app',
    data: function() {
      return {
          dialogImageUrl: '',
          dialogVisible: false,
          weibo:{content:"",url:""}
      }
    },
    methods:{
        insert(){
            if(this.weibo.url==""){
                alert("请上传图片!");
                return;
            }
            //发出新增微博的异步请求
            axios.post("/insert",this.weibo).then(function () {
                location.href = "/";//返回首页
            })
        },
        handleSuccess(response,file,fileList){
            //此方法是上传文件成功后调用的方法，response代表服务器响应的数据，
            // file代表上传成功的图片，fileList成功上传一组图片的数组
            //上传成功后把服务器响应的图片路径赋值给微博对象
            this.weibo.url = response;
        },
        handleRemove(file, fileList) {
            //因为图片删除了，所以微博对象里面的图片路径应该被清空
            this.weibo.url = "";
            console.log(file, fileList);
            //发出异步的删除请求,file.response代表服务器上传成功时响应的文件路径
            axios.post("/remove?url="+file.response).then(function () {
                 console.log("删除成功");
            })
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        }
    }
  })
</script>
</html>